﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PagerControl
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:Pager runat=server></{0}:Pager>")]
    public class Pager : WebControl
    {
        #region Fields
        private int defaultWidthButton = 16;
        private int defaultWidthTextbox = 15;      
        private string textCSS = "xtb-text";
        private string buttonFirstImageUrl = "~/App_Themes/Admin/images/Pager/page-first.gif";
        private string buttonFirstDisableImageUrl = "~/App_Themes/Admin/images/Pager/page-first-disabled.gif";
        private string buttonPrevImageUrl = "~/App_Themes/Admin/images/Pager/page-prev.gif";
        private string buttonPrevDisableImageUrl = "~/App_Themes/Admin/images/Pager/page-prev-disabled.gif";
        private string buttonNextImageUrl = "~/App_Themes/Admin/images/Pager/page-next.gif";
        private string buttonNextDisableImageUrl = "~/App_Themes/Admin/images/Pager/page-next-disabled.gif";
        private string buttonLastImageUrl = "~/App_Themes/Admin/images/Pager/page-last.gif";
        private string buttonLastDisableImageUrl = "~/App_Themes/Admin/images/Pager/page-last-disabled.gif";
        private int _TotalRecord;
        private int _SelectRecord;
        private int _BeginCurrentRowIndex;//index of the first row of total row
        private int _EndCurrentRowIndex;//index of the last rowo f total row
        #endregion

        #region Control
        private Table tblParent = new Table();
        private Panel pnParent = new Panel();
        private ImageButton ibtnFirst = new ImageButton();
        private ImageButton ibtnPrev = new ImageButton();
        private ImageButton ibtnNext = new ImageButton();
        private ImageButton ibtnLast = new ImageButton();
        private TextBox txtCurrentPage = new TextBox();
        private Button btnGoPage = new Button();
        private DropDownList drlPageSize = new DropDownList();
        private string summaryText = "Show {0}-{1} of {2} items";
        private bool showSumaryText = true;
        private string totalPageLabel = " of {0}";
        private string pageSizeLabel = "Page size";
        private string pageLabel = "Page";

        #endregion

        #region Control Properies
        public int PageIndex
        {

            get
            {

                object o = ViewState["PageIndex"];
                if (o != null) return (int)o;
                return 1;
            }

            set { ViewState["PageIndex"] = value; }

        }
        public int TotalPage
        {

            get
            {

                object o = ViewState["TotalPage"];
                if (o != null) return (int)o;
                return 1;
            }

            set { ViewState["TotalPage"] = value; }

        }
        [Browsable(false)]
        [Description("Current row in page")]
        public int SelectRecord
        {
            get
            {
                return _SelectRecord;
            }
            set
            {
                _SelectRecord = value;
            }
        }

        [Browsable(true)]
        [Description("Gets or sets the My Property.")]
        public int PageSize
        {
            get
            {
                return int.Parse(drlPageSize.SelectedValue);
            }
            set
            {
                int _PageSize = value;
                if (_PageSize <= 0)
                    _PageSize = 1;
                if (_PageSize > int.MaxValue)
                    _PageSize = int.MaxValue;
                drlPageSize.SelectedValue = _PageSize.ToString();
            }
        }
        [Browsable(false)]
        [Description("Total record of result")]
        public int TotalRecord
        {
            get
            {
                return _TotalRecord;
            }
            set
            {
                _TotalRecord = value;
            }
        }
        public bool ShowSumaryText
        {
            get
            {
                return showSumaryText;
            }
            set { showSumaryText = value; }
        }
        #endregion

        #region Init Control

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitControl();
        }

        #endregion

        #region Delegate
        public delegate void ChangePageSize(object obj, PageSizeChangeEventArgs e);
        public event ChangePageSize PageSizeChanging;
        public delegate void ChangePageIndex(object obj, PageIndexChangeEventArgs e);
        public event ChangePageIndex PageIndexChanging;
        #endregion

        #region Methods
        /// <summary>
        /// Check if current page is the last page
        /// </summary>
        /// <returns></returns>
        public bool IsLastPage()
        {
            if (TotalPage == 0)
                return true;
            if (PageIndex == TotalPage)
                return true;
            return false;
        }
        /// <summary>
        /// Check if current page is the first page
        /// </summary>
        /// <returns></returns>
        public bool IsFirstPage()
        {
            if (TotalPage == 0)
                return true;
            if (PageIndex == 1)
                return true;
            return false;
        }
        /// <summary>
        /// Find index  of the first row
        /// </summary>
        private void SetBeginRowIndex()
        {
            this._BeginCurrentRowIndex = (this.PageIndex - 1) * int.Parse(drlPageSize.SelectedValue) + 1;
        }
        /// <summary>
        /// Find index  of the last row
        /// </summary>
        private void SetEndRowIndex()
        {
            this._EndCurrentRowIndex = this._BeginCurrentRowIndex + this.SelectRecord - 1;
        }
        private void InitControl()
        {
           
            ibtnFirst.ImageUrl = this.buttonFirstImageUrl;
            ibtnPrev.ImageUrl = this.buttonPrevImageUrl;
            ibtnNext.ImageUrl = this.buttonNextImageUrl;
            ibtnLast.ImageUrl = this.buttonLastImageUrl;
           
            //register event for button
            ibtnFirst.Click += new ImageClickEventHandler(ibtnFirst_Click);
            ibtnPrev.Click += new ImageClickEventHandler(ibtnPrev_Click);
            ibtnNext.Click += new ImageClickEventHandler(ibtnNext_Click);
            ibtnLast.Click += new ImageClickEventHandler(ibtnLast_Click);
           
            btnGoPage.Click += new EventHandler(btnGoPage_Click);
            txtCurrentPage.MaxLength = 3;
            btnGoPage.Text = "Go";
            this.btnGoPage.Width = 36;
            btnGoPage.CssClass = "button_s";
            //this.btnGoPage.Height = btnLast.Height = this.btnNext.Height = this.btnPrev.Height = this.btnFirst.Height = defaultHeightControl;
            this.txtCurrentPage.Width = defaultWidthTextbox;
            TableRow tr = new TableRow();
            TableCell cell = new TableCell();
            cell.Text = string.Empty;
            cell.Attributes.Add("width", "auto");
            tr.Controls.AddAt(0, cell);//add  empty cell;
            cell = new TableCell();
            cell.Width = 150;
            cell.HorizontalAlign = HorizontalAlign.Right;
            cell.VerticalAlign = VerticalAlign.Top;
            cell.Text = string.Format(summaryText, 1, 10, 20);
            tr.Controls.AddAt(1, cell);//add cell sumary;
            ///ad cell Pagesize
            cell = new TableCell();
            cell.Width = 80;
            cell.Text = pageSizeLabel;
            cell.Attributes.Add("class", textCSS);
            cell.HorizontalAlign = HorizontalAlign.Right;
            tr.Controls.AddAt(2, cell);
            ///add droplist page size
            cell = new TableCell();
            InitPageSize();
            cell.Width = 50;
            cell.HorizontalAlign = HorizontalAlign.Left;
            cell.Controls.Add(drlPageSize);
            tr.Controls.AddAt(3, cell);           
            cell = new TableCell();
            cell.Width = defaultWidthButton + 5;
            cell.HorizontalAlign = HorizontalAlign.Center;          
            cell.Controls.Add(ibtnFirst);           
            tr.Controls.AddAt(4, cell);
            //add button btnPrev
            cell = new TableCell();
            cell.Width = defaultWidthButton + 5;
            cell.HorizontalAlign = HorizontalAlign.Center;
            cell.Controls.Add(ibtnPrev);
            tr.Controls.AddAt(5, cell);
            //add Page Label 
            cell = new TableCell();
            cell.Width = 40;
            cell.HorizontalAlign = HorizontalAlign.Right;
            cell.Text = pageLabel;
            cell.Attributes.Add("class", textCSS);
            tr.Controls.AddAt(6, cell);
            //add textbox page value
            cell = new TableCell();
            cell.Width = defaultWidthTextbox + 5;
            cell.HorizontalAlign = HorizontalAlign.Center;
            cell.Controls.Add(txtCurrentPage);
            tr.Controls.AddAt(7, cell);

            //add label total page
            cell = new TableCell();
            cell.Width = 40;
            cell.HorizontalAlign = HorizontalAlign.Left;
            cell.Text = string.Format(totalPageLabel, 3);
            cell.Attributes.Add("class", textCSS);
            tr.Controls.AddAt(8, cell);


            //add btnNext
            cell = new TableCell();
            cell.Width = defaultWidthButton + 5;
            cell.HorizontalAlign = HorizontalAlign.Center;
            cell.VerticalAlign = VerticalAlign.Middle;
            cell.Controls.Add(ibtnNext);
            tr.Controls.AddAt(9, cell);

            //add btnLast
            cell = new TableCell();
            cell.Width = defaultWidthButton + 5;
            cell.HorizontalAlign = HorizontalAlign.Center;
            cell.Controls.Add(ibtnLast);
            tr.Controls.AddAt(10, cell);
            //add btnGo
            cell = new TableCell();
            cell.Width = 30;
            cell.HorizontalAlign = HorizontalAlign.Center;
            cell.Controls.Add(btnGoPage);
            tr.Controls.AddAt(11, cell);
            tblParent.Rows.Add(tr);            
            this.Attributes.Add("class", "x-toolbar");            
            this.tblParent.Attributes.Add("class", "x-pager-table");
            this.Controls.Add(tblParent);
           
        }

        
        private void InitPageSize()
        {
            //this.drlPageSize.Items.Add(new ListItem("2", "2"));
            //this.drlPageSize.Items.Add(new ListItem("5", "5"));
            this.drlPageSize.Items.Add(new ListItem("10", "10"));
            this.drlPageSize.Items.Add(new ListItem("20", "20"));
            this.drlPageSize.Items.Add(new ListItem("50", "50"));
            this.drlPageSize.Items.Add(new ListItem("100", "100"));
            this.drlPageSize.Items.Add(new ListItem("200", "200"));
            //this.drlPageSize.Items.Add(new ListItem("Tất cả", int.MaxValue.ToString()));
            drlPageSize.SelectedIndexChanged += new EventHandler(drlPageSize_SelectedIndexChanged);
            drlPageSize.AutoPostBack = true;

        }
        protected override void RenderContents(HtmlTextWriter output)
        {
            this.tblParent.RenderControl(output);
        }
        public void SetPaging(int pageIndex,int selectRow ,int totalRow)
        {
            //Found total page
            if (selectRow <= 0)
            {
                this.Visible = false;
                return;
            }
            this.Visible = true;
            this.PageIndex = pageIndex;
            this.SelectRecord = selectRow;
            this.TotalRecord = totalRow;
            txtCurrentPage.Text = PageIndex.ToString();
            this.TotalPage = this._TotalRecord / int.Parse(drlPageSize.SelectedValue);
            if (this._TotalRecord % int.Parse(drlPageSize.SelectedValue) != 0)
                this.TotalPage++;
            SetBeginRowIndex();
            SetEndRowIndex();
            if (IsFirstPage())
            {
                ibtnFirst.ImageUrl=this.buttonFirstDisableImageUrl;
                ibtnPrev.ImageUrl = this.buttonPrevDisableImageUrl;
                ibtnFirst.Attributes.Add("onclick", "javascript:return false;");
                ibtnPrev.Attributes.Add("onclick", "javascript:return false;");
            }
            else
            {
                ibtnFirst.ImageUrl = this.buttonFirstImageUrl;
                ibtnPrev.ImageUrl = this.buttonPrevImageUrl;
                ibtnFirst.Attributes.Add("onclick", "javascript:return true;");
                ibtnPrev.Attributes.Add("onclick", "javascript:return true;");
            }
            if (IsLastPage())
            {
                ibtnNext.ImageUrl = this.buttonNextDisableImageUrl;
                ibtnLast.ImageUrl = this.buttonLastDisableImageUrl;
                ibtnNext.Attributes.Add("onclick", "javascript:return false;");
                ibtnLast.Attributes.Add("onclick", "javascript:return false;");
            }
            else
            {
                ibtnNext.ImageUrl = this.buttonNextImageUrl;
                ibtnLast.ImageUrl = this.buttonLastImageUrl;
                ibtnNext.Attributes.Add("onclick", "javascript:return true;");
                ibtnLast.Attributes.Add("onclick", "javascript:return true;");
            }
            TableCell cell = new TableCell();
            cell = this.tblParent.Rows[0].Cells[8];
            cell.Text = string.Format(totalPageLabel, this.TotalPage);
            cell = this.tblParent.Rows[0].Cells[1];
            if (showSumaryText)
                cell.Text = string.Format(summaryText, this._BeginCurrentRowIndex, _EndCurrentRowIndex, TotalRecord);
            else
                cell.Visible = false;
        }
        #endregion

        #region Events Handle
        void btnGoPage_Click(object sender, EventArgs e)
        {
            ibtnFirst.ImageUrl = this.buttonFirstDisableImageUrl;
            int page = 1;
            try
            {
                page = int.Parse(txtCurrentPage.Text);
            }
            catch
            {
            }
            if (page < 1)
                page = 1;
            if (page > TotalPage)
                page = 1;
            if (PageIndexChanging != null)
            {
                PageIndexChanging(this, new PageIndexChangeEventArgs(page));
            }
        }
        void btnLast_Click(object sender, EventArgs e)
        {
            if (PageIndexChanging != null)
            {
                PageIndexChanging(this, new PageIndexChangeEventArgs(this.TotalPage));
            }
        }
        void btnNext_Click(object sender, EventArgs e)
        {
            if (PageIndexChanging != null)
            {
                PageIndexChanging(this, new PageIndexChangeEventArgs(this.PageIndex + 1));
            }
        }
        void btnPrev_Click(object sender, EventArgs e)
        {
            if (PageIndexChanging != null)
            {
                PageIndexChanging(this, new PageIndexChangeEventArgs(this.PageIndex - 1));
            }
        }
        void btnFirst_Click(object sender, EventArgs e)
        {
            if (PageIndexChanging != null)
            {
                PageIndexChanging(this, new PageIndexChangeEventArgs(1));
            }
        }
        void drlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (PageSizeChanging != null)
            {

                PageSizeChanging(this, new PageSizeChangeEventArgs(int.Parse(drlPageSize.SelectedValue)));

            }
        }
        void ibtnLast_Click(object sender, ImageClickEventArgs e)
        {
            if (PageIndexChanging != null)
            {
                PageIndexChanging(this, new PageIndexChangeEventArgs(this.TotalPage));
            }
        }

        void ibtnNext_Click(object sender, ImageClickEventArgs e)
        {
            if (PageIndexChanging != null)
            {
                PageIndexChanging(this, new PageIndexChangeEventArgs(this.PageIndex + 1));
            }
        }

        void ibtnPrev_Click(object sender, ImageClickEventArgs e)
        {
            if (PageIndexChanging != null)
            {
                PageIndexChanging(this, new PageIndexChangeEventArgs(this.PageIndex - 1));
            }
        }

        void ibtnFirst_Click(object sender, ImageClickEventArgs e)
        {
            if (PageIndexChanging != null)
            {
                PageIndexChanging(this, new PageIndexChangeEventArgs(1));
            }
        }
        #endregion
    }
}
